<template>
  <div class="home">
    <!-- 轮播图 -->
    <!-- <v-slide-group
      v-model="model"
      show-arrows
      style="height: 315px; width: 100vw; max-width: 1200px"
      class="d-none d-sm-flex"
    >
      <v-slide-item
        v-for="(item, i) in detail.images"
        :key="i"
        v-slot="{ active, toggle }"
        style="width: 560px; height: 315px"
      >
        <v-card :color="active ? '' : ''" class="ma-4" @click="toggle">
          <v-img height="315" width="560" :src="item" />
        </v-card>
      </v-slide-item>
    </v-slide-group> -->
    <!-- Slider main container -->
    <div
      v-if="detail && (!detail.images || detail.images.length > 1)"
      class="swiper-wrapper d-none d-sm-flex"
      style="height: 315px; width: 100vw; max-width: 1200px"
    >
      <div v-swiper:mySwiper="swiperOptions" class="swiper-container">
        <div class="swiper-wrapper">
          <div v-for="(item, index) in detail.images" :key="index" class="swiper-slide">
            <img
              :src="item"
              style="height: 315px; width: 560px"
              :alt="`Slide ${index}`"
              loading="lazy"
              class="slide-image"
            />
          </div>
        </div>

        <!-- 导航箭头 -->
        <div class="swiper-button-prev" />
        <div class="swiper-button-next" />
      </div>
    </div>
    <div
      v-else
      class="swiper-wrapper d-none d-sm-flex"
      style="height: 315px; width: 100vw; max-width: 1200px"
    >
      <div class="swiper-container">
        <div class="swiper-wrapper">
          <div
            v-for="(item, index) in detail.images"
            :key="index"
            class="swiper-slide"
            style="opacity: 1"
          >
            <img
              :src="item"
              style="height: 315px; width: 560px"
              :alt="`Slide ${index}`"
              loading="lazy"
              class="slide-image"
            />
          </div>
        </div>
      </div>
    </div>

    <v-carousel class="d-block d-sm-none" height="56.25vw" hide-delimiters :show-arrows="false">
      <v-carousel-item v-for="(item, i) in detail.images" :key="i">
        <v-img :src="item" />
      </v-carousel-item>
    </v-carousel>

    <v-row class="px-150 mt-16">
      <v-col xs="12" sm="12" md="6">
        <v-row class="title">
          {{ detail.carmodel ? detail.carmodel.model_num : '' }}
        </v-row>
        <v-row>
          <h1 class="car-name">{{ detail.name }}</h1>
        </v-row>
        <v-row align="center" class="desc-1 pt-4">
          <v-spacer>
            <div class="desc-icon">
              <v-icon color="darken-2" size="20px" class="mr-1">{{ icons.mdiAccount }}</v-icon>
              <span class="mr-5">{{ detail.seats }}</span>
            </div>
            <div v-if="detail.automatic == '1'" class="desc-icon">
              <v-icon color="darken-2" size="20px" class="mr-1">{{ icons.mdiWrench }}</v-icon>
              <span class="mr-5">{{ $t('automatic') }}</span>
            </div>
            <div v-else class="desc-icon">
              <v-icon color="darken-2" size="20px" class="mr-1">{{ icons.mdiWrench }}</v-icon>
              <span class="mr-5">{{ $t('noautomatic') }}</span>
            </div>
            <div class="desc-icon">
              <v-icon color="darken-2" size="20px" class="mr-1">{{ icons.mdiHome }}</v-icon>
              <span>{{ detail.store?.name }}</span>
            </div>
          </v-spacer>
        </v-row>
        <v-row class="desc mt-9" v-html="detail.content" />

        <!-- 性能 -->
        <v-row class="spec mt-10 mb-6">
          {{ $t('spec') }}
        </v-row>
        <v-row class="mt-10 mb-6">
          <v-col v-if="detail.displacement" :cols="12" :sm="6">
            <v-icon color="#09d299" :size="16">{{ icons.mdiCheck }}</v-icon>
            <span class="spec-txt"> {{ $t('displacement') }} : {{ detail.displacement }} </span>
          </v-col>
          <v-col v-if="detail.max_output" :cols="12" :sm="6">
            <v-icon color="#09d299" :size="16">{{ icons.mdiCheck }}</v-icon>
            <span class="spec-txt"> {{ $t('max_output') }} : {{ detail.max_output }} </span>
          </v-col>
          <v-col v-if="detail.max_torque" :cols="12" :sm="6">
            <v-icon color="#09d299" :size="16">{{ icons.mdiCheck }}</v-icon>
            <span class="spec-txt"> {{ $t('max_torque') }} : {{ detail.max_torque }} </span>
          </v-col>
          <v-col v-if="detail.transmission" :cols="12" :sm="6">
            <v-icon color="#09d299" :size="16">{{ icons.mdiCheck }}</v-icon>
            <span class="spec-txt"> {{ $t('transmission') }} : {{ detail.transmission }} </span>
          </v-col>
          <v-col v-if="detail.seats" :cols="12" :sm="6">
            <v-icon color="#09d299" :size="16">{{ icons.mdiCheck }}</v-icon>
            <span class="spec-txt"> {{ $t('seats') }} : {{ detail.seats }} </span>
          </v-col>
          <v-col v-if="detail.length" :cols="12" :sm="6">
            <v-icon color="#09d299" :size="16">{{ icons.mdiCheck }}</v-icon>
            <span class="spec-txt"> {{ $t('length') }} : {{ detail.length }} </span>
          </v-col>
          <v-col v-if="detail.width" :cols="12" :sm="6">
            <v-icon color="#09d299" :size="16">{{ icons.mdiCheck }}</v-icon>
            <span class="spec-txt"> {{ $t('width') }} : {{ detail.width }} </span>
          </v-col>
          <v-col v-if="detail.height" :cols="12" :sm="6">
            <v-icon color="#09d299" :size="16">{{ icons.mdiCheck }}</v-icon>
            <span class="spec-txt"> {{ $t('height') }} : {{ detail.height }} </span>
          </v-col>
        </v-row>

        <!-- 设备 -->
        <v-row class="price mt-10 mb-6">
          {{ $t('option') }}
        </v-row>
        <v-row>
          <v-simple-table class="table" fixed-header height="160px">
            <template #default>
              <tbody>
                <tr v-for="(item, i) in detail.device" :key="i">
                  <td>{{ item.name }}</td>
                  <td>{{ $t('coin') }}{{ item.price }}</td>
                </tr>
              </tbody>
            </template>
          </v-simple-table>
        </v-row>

        <!-- 价格 -->
        <v-row class="price mt-10 mb-6">
          {{ $t('price') }}
        </v-row>
        <v-row>
          <v-simple-table class="table" fixed-header height="340px">
            <template #default>
              <thead>
                <tr>
                  <th class="text-left">
                    {{ $t('times') }}
                  </th>
                  <th class="text-center" colspan="2">
                    {{ $t('price') }}
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="detail.price && detail.price.three_hourprice != 0">
                  <td>3 H</td>
                  <td class="text-right">
                    {{ $t('coin') }} {{ detail.price.three_hourprice | coinF }}
                  </td>
                  <td
                    v-if="
                      detail.price.three_hourprice_origin &&
                      detail.price.three_hourprice_origin != 0
                    "
                    class="strikethrough"
                  >
                    {{ $t('coin') }} {{ detail.price.three_hourprice_origin | coinF }}
                  </td>
                  <td v-else />
                </tr>
                <tr
                  v-if="
                    detail.price && detail.price.six_hourprice && detail.price.six_hourprice != 0
                  "
                >
                  <td>6 H</td>
                  <td class="text-right">
                    {{ $t('coin') }} {{ detail.price.six_hourprice | coinF }}
                  </td>
                  <td
                    v-if="
                      detail.price.six_hourprice_origin && detail.price.six_hourprice_origin != 0
                    "
                    class="strikethrough"
                  >
                    {{ $t('coin') }} {{ detail.price.six_hourprice_origin | coinF }}
                  </td>
                  <td v-else />
                </tr>

                <tr v-if="detail.price && detail.price.daysprice != 0">
                  <td>24 H</td>
                  <td class="text-right">{{ $t('coin') }} {{ detail.price.daysprice | coinF }}</td>
                  <td
                    v-if="detail.price.daysprice_origin && detail.price.daysprice_origin != 0"
                    class="strikethrough"
                  >
                    {{ $t('coin') }} {{ detail.price.daysprice_origin | coinF }}
                  </td>
                  <td v-else />
                </tr>
                <tr v-if="detail.price && detail.price.dayout_daysprice != 0">
                  <td>{{ $t('thereafter') }} 24H</td>
                  <td class="text-right">
                    {{ $t('coin') }} {{ detail.price.dayout_daysprice | coinF }}
                  </td>
                  <td
                    v-if="
                      detail.price.dayout_daysprice_origin &&
                      detail.price.dayout_daysprice_origin != 0
                    "
                    class="strikethrough"
                  >
                    {{ $t('coin') }} {{ detail.price.dayout_daysprice_origin | coinF }}
                  </td>
                  <td v-else />
                </tr>
                <tr v-if="detail.price && detail.price.cdw_price != 0">
                  <td>{{ $t('cdw') }}</td>
                  <td class="text-right">{{ $t('coin') }} {{ detail.price.cdw_price | coinF }}</td>
                  <td class="text-left" />
                </tr>
              </tbody>
            </template>
          </v-simple-table>
        </v-row>

        <!-- 门店 -->
        <v-row class="shop mt-10 mb-6">
          {{ $t('storedetail') }}
        </v-row>
        <v-row class="my-10">
          <div class="desc">
            <div class="desc-label">{{ $t('storename') }}:</div>
            <div class="desc-value">{{ detail.store?.name }}</div>
          </div>
          <div class="desc">
            <div class="desc-label">{{ $t('storeaddress') }}:</div>
            <div class="desc-value">{{ detail.store?.address }}</div>
          </div>
          <div class="desc">
            <div class="desc-label">{{ $t('onlinetime') }}:</div>
            <div class="desc-value">
              {{
                detail.store?.business_start &&
                detail.store.business_start.toString().padStart(2, '0')
              }}
              :00 -
              {{
                detail.store?.business_end && detail.store.business_end.toString().padStart(2, '0')
              }}
              : 00
            </div>
          </div>
          <div class="desc">
            <div class="desc-label">{{ $t('contract') }}:</div>
            <div class="desc-value">{{ detail.store?.contacts }}</div>
          </div>
          <div class="desc">
            <div class="desc-label">{{ $t('phone') }}:</div>
            <div class="desc-value">{{ detail.store?.phone }}</div>
          </div>
          <div class="desc">
            <div class="desc-label">{{ $t('eamil') }}:</div>
            <div class="desc-value">{{ detail.store?.email }}</div>
          </div>
        </v-row>
        <!-- 地址 -->
        <v-row class="price mt-10 mb-6">
          {{ $t('pickupaddress') }}
        </v-row>
        <v-row class="my-10">
          <iframe
            :src="detail.store ? detail.store.map_src : ''"
            width="600"
            height="450"
            style="border: 0; width: 100%"
            allowfullscreen=""
            loading="lazy"
            referrerpolicy="no-referrer-when-downgrade"
          />
        </v-row>
        <!-- 预定须知 -->
        <v-row class="note-title mt-10 mb-6">
          {{ $t('notesonreservation') }}
        </v-row>
        <v-row class="note" v-html="detail.store ? detail.store.booking_notice : ''" />
      </v-col>

      <!-- 步骤 -->
      <v-col xs="12" sm="12" md="6" class="pl-16">
        <div class="card pa-6 mt-7 datepicker-A">
          <v-row no-gutters class="step">
            {{ $t('step1') }}
          </v-row>
          <v-row id="beginDate" no-gutters class="mt-10">
            <SaleCalender
              v-model="formData.beginDate"
              :disable-data="disableData"
              :check-date-is-full-sale="checkDateIsFullSale"
              @change="handleBeginDateChange"
              @picker="handlePicker"
            />
          </v-row>
          <v-row v-if="saleTimes && detail.store">
            <SaleTime
              :sale-times="saleTimes"
              :start-time="detail.store.business_start"
              :end-time="detail.store.business_end"
              @select="handleSelectBeginTime"
            />
          </v-row>
        </div>
        <div class="card pa-6 mt-7">
          <v-row no-gutters class="step">
            {{ $t('step2') }}
          </v-row>
          <v-row no-gutters class="mt-7">
            <v-col>
              <v-row no-gutters>
                {{ $t('pickupdate') }}
              </v-row>
              <v-row no-gutters>
                <date-picker
                  :value="formData.beginDate"
                  placeholder="Pick-up Date"
                  disabled
                  :editable="false"
                  value-type="format"
                  format="YYYY-MM-DD"
                />
              </v-row>
            </v-col>
            <v-col id="beginTime">
              <v-row no-gutters>
                {{ $t('pickuptime') }}
              </v-row>
              <v-row no-gutters>
                <date-picker
                  v-model="formData.beginTime"
                  format="HH:mm"
                  :open.sync="beginPickerOpen"
                  :disabled="!formData.beginDate"
                  :hour-options="beginTimeHourOptions"
                  :minute-options="[0, 30]"
                  :disabled-time="beginDisabledTime"
                  value-type="format"
                  type="time"
                  placeholder="Pick-up Time"
                  :editable="false"
                  @change="handleBeginTimeChange"
                />
              </v-row>
            </v-col>
          </v-row>
          <v-row no-gutters class="mt-7">
            <v-col id="endDate">
              <v-row no-gutters>
                {{ $t('dropoffdate') }}
              </v-row>
              <v-row no-gutters>
                <date-picker
                  v-model="formData.endDate"
                  placeholder="Drop-off Date"
                  :disabled-date="disableEndDay"
                  :disabled="!formData.beginTime"
                  :editable="false"
                  popup-class="select-time-popup"
                  value-type="format"
                  format="YYYY-MM-DD"
                  @change="handleEndDateChange"
                />
              </v-row>
            </v-col>
            <v-col id="endTime">
              <v-row no-gutters>
                {{ $t('dropofftime') }}
              </v-row>
              <v-row no-gutters>
                <date-picker
                  v-model="formData.endTime"
                  :disabled="!formData.endDate"
                  format="HH:mm"
                  :open.sync="endPickerOpen"
                  :hour-options="makeHourOptions()"
                  :minute-options="[0, 30]"
                  :disabled-time="endDisabledTime"
                  value-type="format"
                  type="time"
                  placeholder=" Drop-off Time"
                  :editable="false"
                  @change="handleEndTimeChange"
                />
              </v-row>
            </v-col>
          </v-row>
        </div>
        <div class="card pa-6 mt-7">
          <v-row no-gutters class="step">
            {{ $t('step3') }}
          </v-row>
          <v-row
            id="device"
            no-gutters
            align="center"
            class="mt-5 pl-4 py-4 option"
            style="padding-right: 8px"
          >
            <span class="title mr-7">
              {{ $t('option') }}
            </span>
            <v-col :cols="12">
              <v-row
                v-for="(item, i) in detail.device"
                :key="i"
                class="device-row"
                no-gutters
                align="center"
                justify="space-between"
              >
                <v-col :cols="6">
                  <v-checkbox
                    v-model="formData.device_ids"
                    class="device-row-checkbox"
                    hide-details
                    multiple
                    :label="item.name"
                    :value="item.id"
                  />
                </v-col>
                <v-col
                  v-if="item.number_show === 1"
                  :cols="6"
                  style="display: flex; justify-content: end"
                >
                  <v-text-field
                    v-model="item.number"
                    class="device-row-input"
                    outlined
                    dense
                    hide-details
                    @blur="(val) => handleNumberBlur(val, item)"
                  >
                    <template #prepend> x </template>
                    <template #append-outer>
                      {{ item.unit_name }}
                    </template>
                  </v-text-field>
                </v-col>
                <v-col
                  v-if="item.price_type === 'day'"
                  :cols="item.number_show === 1 ? 12 : 6"
                  style="text-align: right"
                >
                  <span class="device-row-day"> x {{ leaseDay }}{{ $t('day') }} </span>
                </v-col>
                <v-col
                  :cols="item.number_show === 1 || item.price_type === 'day' ? 12 : 6"
                  style="text-align: right"
                >
                  <span class="devive-row-price"> {{ $t('coin') }}{{ calculatePrice(item) }} </span>
                </v-col>
              </v-row>
            </v-col>
          </v-row>
          <v-row no-gutters align="center" class="mt-5 pl-4 py-4 option">
            <div
              class="title mr-7"
              style="margin-bottom: 4px; display: flex; align-items: center; cursor: pointer"
              @click="cdwDialog = true"
            >
              <span style="margin-right: 4px">{{ $t('cdw') }}</span>
              <v-icon size="20px">mdi-help-circle-outline</v-icon>
            </div>
            <v-radio-group v-model="formData.cdw" class="mt-0" hide-details row>
              <v-radio :label="`Subscription`" :value="true" />
              <v-radio :label="`Not subscribed`" :value="false" />
            </v-radio-group>
          </v-row>
          <v-row no-gutters align="center" justify="space-between" class="mt-5 px-4 py-2 option">
            <span class="title mr-7">
              {{ $t('decode') }}
            </span>
            <v-text-field
              v-model="formData.discount_code"
              solo
              dense
              flat
              outlined
              :label="$t('decode')"
              hide-details
              @blur="getPrice"
            />
          </v-row>
        </div>

        <div class="card pa-6 mt-7">
          <v-row no-gutters class="mt-5 step">
            {{ $t('step4') }}
          </v-row>
          <v-row no-gutters align="center" justify="space-between" class="mt-1 pl-4 py-4">
            <span class="title mr-7">
              {{ $t('basicprice') }}
            </span>
            <span class="price-confirm mr-7">
              {{ $t('coin') }} {{ totalPrice.rentFee | coinF }}
            </span>
          </v-row>
          <v-row no-gutters align="center" justify="space-between" class="mt-1 pl-4 py-4">
            <span class="title mr-7">
              {{ $t('optionprice') }}
            </span>
            <span class="price-confirm mr-7">
              {{ $t('coin') }} {{ totalPrice.deviceFee | coinF }}
            </span>
          </v-row>
          <v-row
            v-for="item in totalPrice.deviceFeeList"
            :key="item.name"
            no-gutters
            align="center"
            justify="space-between"
            class="mt-1 pl-4 py-4"
          >
            <span class="title2 ml-4 mr-7">
              <span>{{ item.name }} </span>
              <span v-if="item.unit_name_cn">
                x{{ item.number }}{{ item[`unit_name_${formartLang($i18n.locale)}`] }}
              </span>
              <span v-if="item.price_type === 'day'">x{{ item.days }}{{ $t('day') }}</span>
            </span>
            <span class="price-confirm mr-7" style="font-size: 14px">
              {{ $t('coin') }} {{ item.fee | coinF }}
            </span>
          </v-row>

          <!-- <v-row no-gutters align="center" justify="space-between" class="mt-1 pl-4 py-4">
          <span class="title mr-7">
            {{ $t('depositFee') }}
          </span>
            <span class="price-confirm mr-7">
            {{ $t("coin") }} {{ totalPrice.depositFee | coinF }}
          </span>
          </v-row> -->
          <v-row no-gutters align="center" justify="space-between" class="mt-1 pl-4 py-4">
            <span class="title mr-7">
              {{ $t('cdwprice') }}
            </span>
            <span class="price-confirm mr-7">
              {{ $t('coin') }} {{ totalPrice.cdwFee | coinF }}
            </span>
          </v-row>
          <!-- <v-row STYLE="border-bottom: 1px solid #f1f1f1" no-gutters align="center" justify="space-between"
                 class="mt-1 pl-4 py-4">
            <span class="title mr-7">
              {{ $t('additionaldriverfee') }}
            </span>
            <span class="price-confirm mr-7">
              {{ $t("coin") }} {{ totalPrice.driverFee | coinF }}
            </span>
          </v-row> -->
          <v-row
            s-t-y-l-e="border-bottom: 1px solid #f1f1f1"
            no-gutters
            align="center"
            justify="space-between"
            class="mt-3 pl-4 py-4"
          >
            <span class="title mr-7">
              {{ $t('total') }}
            </span>
            <span class="price-confirm mr-7">
              {{ $t('coin') }} {{ totalPrice.rent_fee_total | coinF }}
            </span>
          </v-row>
          <v-row
            s-t-y-l-e="border-bottom: 1px solid #f1f1f1"
            no-gutters
            align="center"
            justify="space-between"
            class="mt-3 pl-4 py-4"
          >
            <span class="title mr-7">
              {{ $t('totalcount') }}
            </span>
            <span class="price-confirm mr-7" style="color: #ff5252">
              - {{ $t('coin') }} {{ totalPrice.discount_fee | coinF }}
            </span>
          </v-row>
          <v-row
            s-t-y-l-e="border-bottom: 1px solid #f1f1f1"
            no-gutters
            align="center"
            justify="space-between"
            class="mt-3 pl-4 py-4"
          >
            <span class="title mr-7">
              {{ $t('totalpay') }}
            </span>
            <span class="price-confirm mr-7">
              {{ $t('coin') }} {{ totalPrice.totalFee | coinF }}
            </span>
          </v-row>
        </div>
        <v-row class="mt-11 mb-4" justify="center">
          <v-btn dark class="submit" @click="submit">
            {{ $t('continue') }}
          </v-btn>
        </v-row>
      </v-col>
    </v-row>

    <v-dialog v-model="checkStartTimeDialog" width="auto">
      <v-card>
        <v-card-title class="text-h5" style="margin-bottom: 8px">
          {{ $t('tip') }}
        </v-card-title>
        <v-card-text>
          <p>{{ $t('checkStartTimeTitle') }}</p>
          <p>1. {{ $t('checkStartTimeDesc1') }}</p>
          <p>2. {{ $t('checkStartTimeDesc2') }}</p>
          <p>{{ $t('checkStartTimeContact') }}</p>
          <p>1. Instagram： @onlyjdm.tokyo</p>
          <p>
            2. Instagram {{ $t('QRcode') }}：<br />
            <img
              style="width: 200px; height: 200px"
              src="~/assets/instagramQr.jpg"
              alt="instagramQr"
            />
          </p>
        </v-card-text>
        <v-divider />
        <v-card-actions style="flex-wrap: wrap">
          <v-btn
            style="margin: 4px 0; height: 40px"
            color="error"
            @click="checkStartTimeDialog = false"
          >
            {{ $t('checkStartTimeLeftBtn') }}
          </v-btn>
          <v-spacer />
          <v-btn
            color="success"
            style="
              text-align: left;
              display: block;
              flex: unset;
              white-space: unset;
              word-break: break-all;
              margin: 4px 0;
              height: 40px;
            "
            @click="doSubmit"
          >
            {{ $t('checkStartTimeRightBtn') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="cdwDialog" width="auto">
      <img
        style="max-width: 90vw; min-width: 50vw"
        :src="articleInfo ? articleInfo.image : ''"
        alt=""
      />
    </v-dialog>
  </div>
</template>

<script>
import DatePicker from 'vue2-datepicker';
import 'vue2-datepicker/index.css';
// 局部引入，避免全局注册
import { directive } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';

import { mdiAccount, mdiWrench, mdiCheck, mdiHome } from '@mdi/js';
import {
  formartLang,
  getTokyoDaysOfCurrentMonth,
  formatDate,
  formatTime,
  calculateDays
} from '~/utils';
// import pageLoadingMixin from '~/plugins/pageLoadingMixin';

const defaultTotalPrice = () => ({
  hoursTotal: '0', // 小时
  rentFee: '0.00', // 基本租金
  rentFeeDate: {
    '2024-10-25': '0.00',
    '2024-10-26': '0.00',
    '2024-10-27': '0.00',
    '2024-10-28': '0.00',
    '2024-10-29': '0.00',
    '2024-10-30': '0.00'
  },
  deviceFee: '0.00', // etc租金
  deviceFeeList: [],
  totalFee: '0.00', // 总金额
  cdwFee: '0.00', // 免责补传费用
  driverFee: '0.00', // 驾驶员超员金额
  depositFee: '0.00', // 押金
  start_date: '2024-10-25', // 开始日期
  end_date: '2024-10-30', // 结束日期
  rent_fee_total: '0.00', // 总金额
  discount_fee: '0.00' // 优惠金额
});

export default {
  name: 'CarDetail',
  directives: {
    swiper: directive // 局部注册指令
  },
  components: {
    DatePicker
  },
  filters: {
    coinF(number) {
      const numStr = number.toString();
      return numStr.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
  },
  // mixins: [pageLoadingMixin],
  data() {
    return {
      // slides: [
      //   { image: 'https://picsum.photos/400/300?random=1' },
      //   { image: 'https://picsum.photos/400/300?random=2' },
      //   { image: 'https://picsum.photos/400/300?random=3' },
      //   { image: 'https://picsum.photos/400/300?random=4' },
      //   { image: 'https://picsum.photos/400/300?random=5' }
      // ],
      swiperOptions: {
        // 多幻灯片配置
        slidesPerView: 2, // 部分可见下一个幻灯片
        spaceBetween: 20,
        centeredSlides: true,
        // 导航箭头
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev'
        },
        // 断点配置
        breakpoints: {
          640: { slidesPerView: 1 },
          768: { slidesPerView: 1.5 },
          1024: { slidesPerView: 2 }
        }

        // 性能优化
        // preloadImages: false,
        // lazy: true,
        // watchSlidesProgress: true
      },
      icons: {
        mdiAccount,
        mdiWrench,
        mdiCheck,
        mdiHome
      },
      beginPickerOpen: false,
      endPickerOpen: false,
      init: false,
      model: '',
      detail: {},
      calender: {},
      disableData: [],
      formData: {
        start_time: '', // 开始时间 到小时就好
        beginDate: '', // 开始时间 到小时就好
        beginTime: '', // 开始时间 到小时就好
        endDate: '', // 开始时间 到小时就好
        endTime: '', // 开始时间 到小时就好
        end_time: '', // 结束时间 到小时就好
        discount_code: '', // 结束时间 到小时就好
        goods_id: this.$route.params.id || this.$route.query.goods_id, // 产品ID
        device_ids: [], //
        cdw: true, // 是否购买免责补偿
        driver: 1 // 驾驶员人数
      },
      disableDay: '2024-11-26 01:01:00',
      totalPrice: defaultTotalPrice(),
      checkStartTimeDialog: false,
      articleInfo: null,
      cdwDialog: false
    };
  },
  async fetch() {
    await Promise.allSettled([this.getDetailInfo(), this.getArticleInfo(), this.getCalender()]);
  },
  computed: {
    goods_id() {
      // 兼容以前的query参数
      return this.$route.params.id || this.$route.query.goods_id;
    },
    saleTimes() {
      if (!this.formData.beginDate) return;
      return this.calender[this.formData.beginDate];
    },
    beginTimeHourOptions() {
      const options = [];
      this.saleTimes?.forEach((item) => {
        const hourStr = item.split(':')[0];
        options.push(Number(hourStr));
      });
      return Array.from(new Set(options));
    },
    // 租借天数
    leaseDay() {
      const { beginDate, beginTime, endDate, endTime } = this.formData;
      if (!beginDate || !beginTime || !endDate || !endTime) return 1;
      return calculateDays(`${beginDate} ${beginTime}`, `${endDate} ${endTime}`);
    },
    deviceList() {
      return this.formData.device_ids
        .map((item) => this.detail.device.find((it) => it.id === item))
        .filter((item) => item && !!item.number)
        .map((item) => `${item.id}-${item.number}`);
    }
  },
  watch: {
    formData: {
      handler(val) {
        sessionStorage.setItem('carSearchParam', JSON.stringify(val));
      },
      deep: true
    },
    'formData.endTime'() {
      this.getPrice();
    },
    'formData.device_ids'() {
      this.getPrice();
    },
    'formData.cdw'() {
      this.getPrice();
    }
    // 'formData.driver'() {
    //   this.getPrice();
    // }
  },
  mounted() {
    if (sessionStorage.carSearchParam) {
      const oldForm = JSON.parse(sessionStorage.carSearchParam);
      if (oldForm.goods_id === this.goods_id) {
        if (!this.disableData.includes(oldForm.beginDate)) {
          this.init = true;
          this.formData = oldForm;
          this.$nextTick(() => {
            this.init = false;
          });
          this.getEndDate();
        }
      }
      sessionStorage.removeItem('fromSignin');
    }
    console.log(this.$i18n.locale, 222);
  },
  methods: {
    formartLang,
    // 获取产品详情
    async getDetailInfo() {
      const res = await this.$api.post('/product/getInfo', {
        goods_id: this.goods_id // 产品ID
      });
      this.detail = res;
      if (res.device) {
        this.detail.device = res.device.map((item) => ({
          ...item,
          number: 1
        }));
      }
    },
    // 获取cwd弹框内容
    async getArticleInfo() {
      const res = await this.$api.post('/home/getArticleInfo', { type: 7 });
      if (res) {
        this.articleInfo = res;
      }
    },
    // 获取日历上的可销售时间
    async getCalender(date) {
      const allDates = getTokyoDaysOfCurrentMonth(date);
      const res = await this.$api.post('/product/getSaleDate', {
        start_date: allDates[0], // 开始日期
        end_date: allDates[allDates.length - 1], // 结束日期
        goods_id: this.goods_id // 产品ID
      });
      this.calender = {
        ...this.calender,
        ...res
      };
      this.disableData = [];
      Object.keys(res).forEach((key) => {
        if (res[key].length === 0) {
          this.disableData.push(key);
        }
      });
    },
    // 根据开始时间获取最大可选结束时间
    async getEndDate() {
      const { beginDate, beginTime } = this.formData;
      if (!beginDate) return;
      const start_time = `${beginDate} ${beginTime ? beginTime + ':00' : '00:00:00'}`;
      const res = await this.$api.post('/order/getMaxEndTime', {
        start_time,
        goods_id: this.goods_id // 产品ID
      });
      this.disableDay = res;
    },
    async getPrice() {
      const { beginDate, beginTime, endDate, endTime, device_ids, cdw, driver, discount_code } =
        this.formData;

      if (beginDate && beginTime && endDate && endTime) {
        const start_time = `${beginDate} ${beginTime}:00`;
        const end_time = `${endDate} ${endTime}:00`;

        let api = '/order/getTotalFeeNoLogin';
        if (this.$store.state.isLogin) {
          api = '/order/getTotalFee';
        }
        const res = await this.$api.post(api, {
          start_time,
          end_time,
          goods_id: this.goods_id, // 产品ID
          device_ids: device_ids + '', // 是否租聘etc
          deviceList: this.deviceList.join(','),
          cdw, // 是否购买免责补偿
          driver, // 驾驶员人数
          discount_code // 优惠券
        });
        if (res) {
          this.totalPrice = res;
        }
      } else {
        this.totalPrice = defaultTotalPrice();
      }
    },
    // 切月份栏会触发
    handlePicker(date) {
      this.getCalender(date);
    },
    handleBeginDateChange() {
      this.formData.beginTime = '';
      this.formData.endDate = '';
      this.formData.endTime = '';
    },
    handleEndDateChange() {
      this.formData.endTime = '';
    },
    handleSelectBeginTime(time) {
      this.formData.beginTime = time;
      this.handleBeginTimeChange();
      document.getElementById('beginTime').scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    },
    handleBeginTimeChange(value, type) {
      if (type === 'minute') {
        this.beginPickerOpen = false;
      }
      this.formData.endDate = '';
      this.formData.endTime = '';
      this.getEndDate();
    },
    handleEndTimeChange(value, type) {
      if (type === 'hour') return;
      this.endPickerOpen = false;
    },
    beginDisabledTime(date) {
      const time = formatTime(date);
      return !this.saleTimes.includes(time);
    },
    endDisabledTime(date) {
      const time = formatTime(date);
      if (this.formData.endDate === this.formData.beginDate && time === this.formData.beginTime) {
        return true;
      }
      if (
        new Date(`${this.formData.endDate} ${time}:00`).getTime() >
        new Date(this.disableDay).getTime()
      ) {
        return true;
      }
      return ['00:00', '00:30'].includes(time);
    },
    handleNumberBlur(e, item) {
      const value = e.target.value;
      if (/^[1-9]\d*$/.test(value)) {
        item.number = Number(value);
      } else {
        item.number = 1;
      }
      this.getPrice();
    },
    calculatePrice(deviceItem) {
      if (!/^[1-9]\d*$/.test(deviceItem.number)) {
        return 0;
      }
      if (deviceItem.price_type === 'one_time') {
        return deviceItem.price * deviceItem.number;
      } else {
        return deviceItem.price * deviceItem.number * this.leaseDay;
      }
    },
    makeHourOptions() {
      if (!this.detail.store) return;
      const newArr = [];
      // 有两种可能 08:00 08:30
      const startTime = new Date(
        this.formData.beginDate +
          ' ' +
          (this.formData.beginTime ? this.formData.beginTime : '00:00')
      );
      const disabledEndTime = new Date(this.disableDay);
      const { business_start, business_end } = this.detail.store;
      for (let i = business_start; i < business_end; i++) {
        // 只有一种 08:00
        const endTime = new Date(
          this.formData.endDate + ' ' + i.toString().padStart(2, '0') + ':00'
        );
        if (endTime.getTime() <= disabledEndTime.getTime()) {
          if (startTime.getTime() <= endTime.getTime()) {
            newArr.push(i);
          }
        }
      }
      return newArr;
    },
    disableEndDay(date) {
      const beginDate = new Date(this.formData.beginDate);
      beginDate.setHours(0, 0, 0, 0);
      const day = formatDate(date);
      return (
        date < beginDate ||
        date > new Date(this.disableDay) ||
        (this.detail.holsDate && this.detail.holsDate.includes(day))
      );
    },
    checkDateIsFullSale(date) {
      const saleTimes = this.calender[date];
      if (!saleTimes || !this.detail || !this.detail.store) return false;
      const len = this.detail.store.business_end - this.detail.store.business_start;
      if (saleTimes.length < len * 2) return false;
      return true;
    },
    async checkStartTime() {
      const { beginDate, beginTime } = this.formData;
      const start_time = `${beginDate} ${beginTime}:00`;
      const res = await this.$api.post('/order/checkStartTime', {
        start_time
      });
      if (res === false) {
        this.checkStartTimeDialog = true;
        return Promise.reject();
      }
    },
    async doSubmit() {
      try {
        const { beginDate, beginTime, endDate, endTime } = this.formData;
        const start_time = beginDate
          ? `${beginDate} ${beginTime ? beginTime + ':00' : '00:00:00'}`
          : '';
        const end_time = endDate ? `${endDate} ${endTime ? endTime + ':00' : '00:00:00'}` : '';
        const formData = {
          ...this.formData,
          start_time,
          end_time,
          device_ids: this.formData.device_ids.join(','),
          deviceList: this.deviceList.join(',')
        };
        const res = await this.$api.post('/order/createOrder', formData);
        if (res && res.ordersn) {
          const ordersn = res.ordersn; // todo
          sessionStorage.removeItem('carSearchParam');
          this.$router.push(
            this.localePath({
              path: '/payment',
              query: { ordersn }
            })
          );
        }
      } catch (e) {
        console.log(e);
      }
    },
    async submit() {
      let errTargetDom;
      if (!this.formData.beginDate) {
        errTargetDom = document.getElementById('beginDate');
      } else if (!this.formData.beginTime) {
        errTargetDom = document.getElementById('beginTime');
      } else if (!this.formData.endDate) {
        errTargetDom = document.getElementById('endDate');
      } else if (!this.formData.endTime) {
        errTargetDom = document.getElementById('endTime');
      } else if (this.deviceList.length < this.formData.device_ids.length) {
        errTargetDom = document.getElementById('device');
      }

      if (errTargetDom) {
        errTargetDom.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        });
        console.log(errTargetDom);
        return;
      }
      await this.checkStartTime();
      this.doSubmit();
    }
  }
};
</script>
<style lang="scss" scoped>
.desc-icon {
  display: inline-flex;
  align-items: center;
  height: 28px;
}
.device-row {
  margin: 12px 0;
  line-height: 36px;
  .device-row-checkbox {
    margin-top: 0;
    padding-top: 0;
  }
  .device-row-input {
    align-items: center;
    flex: 0;
    :deep(.v-input__control) {
      width: 60px;
      flex-shrink: 0;
      flex-grow: 0;
    }
    :deep(.v-input__slot) {
      min-height: 20px !important;
    }
    :deep(.v-input__append-outer) {
      margin: 0 0 0 6px !important;
    }
    :deep(.v-input__prepend-outer) {
      margin: 0 6px 0 0 !important;
    }
    :deep(input) {
      padding: 4px 0 !important;
    }
  }
  .devive-row-price {
    font-weight: bold;
  }
}
.card {
  background: #ffffff;
  box-shadow: 0px 20px 60px 0px rgba(167, 174, 174, 0.08);
  border-radius: 30px;
}
@media screen and (max-width: 600px) {
  .px-150 {
    padding-left: 20px !important;
    padding-right: 20px !important;
  }
  .pl-16 {
    padding-left: 12px !important;
  }

  .submit {
    width: 80vw !important;
    height: 57px !important;
    background: #342a29;
    border-radius: 16px !important;
  }
}
.px-150 {
  padding-left: 150px;
  padding-right: 150px;
}

.title {
  font-family: Inter, Inter;
  font-weight: 400;
  font-size: 16px;
  color: #64626a;
  line-height: 26px;
  text-align: left;
  font-style: normal;
}

.title2 {
  font-family: Inter, Inter;
  font-weight: 400;
  font-size: 14px;
  color: #64626a;
  line-height: 26px;
  text-align: left;
  font-style: normal;
}

.car-name {
  font-family: Poppins, Poppins;
  font-weight: 600;
  font-size: 34px;
  color: #3b3a40;
  line-height: 51px;
  text-align: left;
  font-style: normal;
}

.step {
  font-family: Poppins, Poppins;
  font-weight: 600;
  font-size: 20px;
  color: #3b3a40;
  line-height: 30px;
  text-align: left;
  font-style: normal;
}

.desc-1 {
  font-family: Inter, Inter;
  font-weight: 400;
  font-size: 18px;
  color: #64626a;
  line-height: 21px;
  text-align: left;
  font-style: normal;
}

.desc {
  font-family: Inter, Inter;
  font-weight: 400;
  font-size: 16px;
  color: #64626a;
  line-height: 30px;
  text-align: left;
  font-style: normal;
}

.spec {
  font-family: Poppins, Poppins;
  font-weight: 600;
  font-size: 22px;
  color: #3b3a40;
  line-height: 33px;
  text-align: left;
  font-style: normal;
}

.shop {
  font-family: Poppins, Poppins;
  font-weight: 600;
  font-size: 22px;
  color: #3b3a40;
  line-height: 33px;
  text-align: left;
  font-style: normal;
}

.price {
  font-family: Poppins, Poppins;
  font-weight: 600;
  font-size: 22px;
  color: #3b3a40;
  line-height: 33px;
  text-align: left;
  font-style: normal;
}

.price-confirm {
  font-family: Poppins, Poppins;
  font-weight: 500;
  font-size: 16px;
  color: #3b3a40;
  line-height: 25px;
  text-align: center;
  font-style: normal;
}

.price-total {
  font-family: Poppins, Poppins;
  font-weight: 500;
  font-size: 20px;
  color: #342a29;
  line-height: 30px;
  text-align: center;
  font-style: normal;
}

.note-title {
  font-family: Poppins, Poppins;
  font-weight: 600;
  font-size: 22px;
  color: #3b3a40;
  line-height: 33px;
  text-align: left;
  font-style: normal;
}

.note {
  font-family: Inter, Inter;
  font-weight: 500;
  font-size: 16px;
  color: #64626a;
  line-height: 26px;
  text-align: left;
  font-style: normal;
}

.submit {
  width: 457px;
  height: 57px !important;
  background: #342a29;
  border-radius: 16px !important;
}

.desc {
  margin-bottom: 8px;
  width: 100%;
  .desc-label {
    font-weight: bold;
    margin-right: 12px;
    display: inline-block;
  }
  .desc-value {
    display: inline-block;
  }
}
</style>
<style lang="scss">
.swiper-container {
  padding: 20px 0;
}

.swiper-slide {
  opacity: 0.4; /* 非活动幻灯片透明度 */
  transition: opacity 0.3s;
}

.swiper-slide-active {
  opacity: 1; /* 活动幻灯片完全可见 */
}

.slide-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.table {
  width: 100%;
}

.spec-txt {
  font-family: Inter, Inter;
  font-weight: 400;
  font-size: 16px;
  color: #64626a;
  line-height: 26px;
  text-align: left;
  font-style: normal;
}

.option {
  background: #ffffff;
  border-radius: 16px;
  border: 1px solid #f1f1f1;
}

.datepicker-A {
  .v-date-picker-table {
    height: 294px;
  }
  .v-date-picker-table .v-date-picker-table__events {
    bottom: 8px;
  }
}

.strikethrough {
  text-decoration: line-through;
  text-align: left;
}

.select-time-popup {
  .mx-time-option {
    text-align: center;
    &.disabled {
      display: none;
    }
  }
  .mx-btn-icon-double-right,
  .mx-btn-icon-double-left {
    display: none;
  }
}
</style>
